import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

/**
 * Vuex全局状态管理
 * @param options {Array} 用于渲染tabs的数组
 */
const store = new Vuex.Store({
  state: {
      options: [],  // {title: '首页管理', path: '/default'}
      activeIndex: '', // 当前激活的标签页path
      tabRefresh: {}, // {'/default':true,...}
      tabRights: {} //{'/default':['main:login',..],...}
  },
  mutations: {
    // 添加tabs
    add_tabs (state, data) {
      this.state.options.push(data);
      this.state.activeIndex = data.path;
      this.state.tabRefresh[data.path] = true;
      sessionStorage.setItem('lxb_tab_active_item', JSON.stringify(data));
      this.state.tabRights[data.path] = data.opsRights;
    },
    // 删除tabs
    delete_tabs (state, path) {
      let index = 0;
      for (let option of state.options) {
        if (option.path === path) {
          break;
        }
        index++;
      }
      this.state.options.splice(index, 1);
    },
    set_active_index (state, index) {
      this.state.activeIndex = index;
      for (let option of state.options) {
        if (option.path === index) {
           // 保存到 sessionStorage
          sessionStorage.setItem('lxb_tab_active_item', JSON.stringify(option));
          break;
        }
      }
      this.state.tabRefresh[index] = false;
    },
    clear_datas(state) {
      this.state.activeIndex = '';
      this.state.options = [];
      this.state.tabRefresh = {};
      this.state.tabRefresh = {};
    },
    set_tab_refresh(state, path) {
      this.state.tabRefresh[path] = true;
    },
    set_tab_rights(state, data) {
      this.state.tabRights[data.path] = data.opsRights;
    }

  }
});

export default store;
